package com.tanhua.sso.service.Impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.AppJwtUtil;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.sso.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    //@Autowired
    //private RocketMQTemplate rocketMQTemplate;


    /**
     * 用户登录
     *
     * @param phone 手机号
     * @param code  验证码
     * @return
     */
    @Override
    public String login(String phone, String code) {
        String rediskey = "CHECK_CODE_" + phone;
        //从redis中取出验证码
        String redisCode = redisTemplate.opsForValue().get(rediskey);
        //校验验证码
        if (!StringUtils.equals(redisCode, code)) {
            //不一致,则返回空
            return null;
        }
        //是否是新用户的标识
        boolean isNew = false;

        //要把redis中的验证码给删除掉
        //redisTemplate.delete(rediskey);
        //一致的情况下，则校验手机号
        //根据手机号去查询mysql数据库
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getMobile, phone));
        //如果不存在，表示新用户，则保存到mysql中
        if (null == user) {
            user = new User();
            user.setMobile(phone);
            //给个初始化密码，000000,并进行md5加密处理
            user.setPassword(DigestUtils.md5Hex("00000"));
            userMapper.insert(user);
            isNew = true;

            //注册环信用户
            Boolean result = this.huanXinApi.register(user.getId());
            if (!result) {
                //注册环信失败，记录日志
                log.error("注册环信用户失败~ userId = " + user.getId());
            }
        }



        //如果存在，则表示老用户，生成Token返回给用户
        String token = AppJwtUtil.getToken(user.getId());

        //返回客户端
        return token + "|" + isNew;
    }

}
